﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using EnvDTE;
using System.Configuration;

namespace Vivasky.T4Helper
{
	public static partial class Utils
	{
		public static Project GetCurrentProject(object t4host) {
			IServiceProvider _ServiceProvider = (IServiceProvider)t4host;
			if (_ServiceProvider == null)
				throw new Exception("Host property returned unexpected value (null)");

			EnvDTE.DTE dte = (EnvDTE.DTE)_ServiceProvider.GetService(typeof(EnvDTE.DTE));
			if (dte == null)
				throw new Exception("Unable to retrieve EnvDTE.DTE");

			Array activeSolutionProjects = (Array)dte.ActiveSolutionProjects;
			if (activeSolutionProjects == null)
				throw new Exception("DTE.ActiveSolutionProjects returned null");

			EnvDTE.Project dteProject = (EnvDTE.Project)activeSolutionProjects.GetValue(0);
			if (dteProject == null)
				throw new Exception("DTE.ActiveSolutionProjects[0] returned null");

			return dteProject;
		}
		public static string GetProjectPath(object t4host)
		{
			EnvDTE.Project project = GetCurrentProject(t4host);
			System.IO.FileInfo info = new System.IO.FileInfo(project.FullName);
			return info.Directory.FullName;
		}

		public static string GetConfigPath(object t4host)
		{
			EnvDTE.Project project = GetCurrentProject(t4host);
			foreach (EnvDTE.ProjectItem item in project.ProjectItems)
			{
				// if it is the app.config file, then open it up
				if (item.Name.Equals("App.config", StringComparison.InvariantCultureIgnoreCase) || item.Name.Equals("Web.config", StringComparison.InvariantCultureIgnoreCase))
					return String.Format("{0}\\{1}", GetProjectPath(t4host), item.Name);
			}
			return String.Empty;
		}

		public static string GetDataDirectory(object t4host)
		{
			EnvDTE.Project project = GetCurrentProject(t4host);
			return String.Format("{0}\\App_Data\\", System.IO.Path.GetDirectoryName(project.FileName));
		}
		public static string GetConnectionString(string connectionStringName,object t4host)
		{
			var _CurrentProject = GetCurrentProject(t4host);

			string result = "";
			ExeConfigurationFileMap configFile = new ExeConfigurationFileMap();
			configFile.ExeConfigFilename = GetConfigPath(t4host);

			if (string.IsNullOrEmpty(configFile.ExeConfigFilename))
				throw new ArgumentNullException("The project does not contain App.config or Web.config file.");


			var config = System.Configuration.ConfigurationManager.OpenMappedExeConfiguration(configFile, ConfigurationUserLevel.None);
			var connSection = config.ConnectionStrings;

			//if the connectionString is empty - which is the defauls
			//look for count-1 - this is the last connection string
			//and takes into account AppServices and LocalSqlServer
			if (string.IsNullOrEmpty(connectionStringName))
			{
				if (connSection.ConnectionStrings.Count > 1)
				{
					result = connSection.ConnectionStrings[connSection.ConnectionStrings.Count - 1].ConnectionString;
				}
			}
			else
			{
				try
				{
					result = connSection.ConnectionStrings[connectionStringName].ConnectionString;
				}
				catch
				{
					result = String.Format("There is no connection string name called '{0}'", connectionStringName);
				}
			}
			if (result.Contains("|DataDirectory|"))
			{
				//have to replace it
				string dataFilePath = GetDataDirectory(t4host);
				result = result.Replace("|DataDirectory|", dataFilePath);
			} 
			return result;
		}
	}
}
